package centralSystem.counters;

import java.util.Random;

import centralSystem.ICentralSystem;
import centralSystem.IPostCounter;

/**
 * Priority service supporting implementation of {@link IPostCounter}.
 * Once a client has been served, and it's time for the counter to call
 * the next one, it tries to call him from the queue of priority service, 
 * but, being it empty, it calls a new client from an other queue (randomly)
 * 
 * @author simone
 *
 */
public class PriorityServiceCounter implements IPostCounter{

	private int priorityService;
	private ICentralSystem centralSystem;
	private int lastService;
	
	public PriorityServiceCounter(ICentralSystem centralSystem, int serviceType) {
		super();
		this.priorityService = serviceType;
		this.centralSystem = centralSystem;
		this.lastService = priorityService;	//TODO: if priorityservice's queue is empty, firs nextService is ineffective
	}

	@Override
	/*
	 * (non-Javadoc)
	 * @see centralSystem.IPostCounter#nextService()
	 */
	public int nextService() {
		
		centralSystem.clientServedAtQueue(lastService);
		if (centralSystem.getTotalClient(priorityService) != centralSystem.getNextClient(priorityService)-1) {
			lastService = priorityService;
			return priorityService;
		}
		Random randomGenerator = new Random(System.nanoTime());
		int nextService= gerenateService(randomGenerator);
		lastService = nextService;
		return nextService;
	}

	private int gerenateService(Random randomGenerator) {
		int nextService = randomGenerator.nextInt(3);
		if (nextService==priorityService) {
			nextService = gerenateService(randomGenerator);
		}
		return nextService;
	}

	@Override
	public int getHandled() {
		return lastService;
	}

}
